<template>
  <div class="my-address">
    <div class="header">
      <div class="title">{{ isOrder ? "确认收货地址" : "我的地址" }}</div>
      <el-button type="primary" :size="size" icon="el-icon-plus" @click="onAdd"
        >新增地址</el-button
      >
    </div>
    <div class="address-list">
      <div
        class="address-card"
        v-for="(item, index) in addressList"
        :key="item.addressId"
        @click="changeCurrentAdsId(item.addressId)"
        :class="{ active: item.addressId === currentAdsId }"
      >
        <el-radio
          v-if="isOrder"
          class="address-checkbox"
          v-model="currentAdsId"
          :label="item.addressId"
        ></el-radio>
        <div class="address-info">
          <div>
            <div>
              <span class="name">{{ item.recipient }}</span>
              <span>{{ item.phone }}</span>
            </div>
            <div class="address-detail">
              <span>{{ item.province }}</span>
              <span>{{ item.city }}</span>
              <span>{{ item.district }}</span>
              <span>{{ item.street }}</span>
              <span>{{ item.detail }}</span>
            </div>
          </div>
          <el-button
            type="text"
            @click.stop="onEdit(item.userId, item.addressId)"
          >
            <i class="el-icon-edit"></i>
          </el-button>
        </div>
        <div class="address-action">
          <el-checkbox
            v-model="item.isDefault"
            @change="(val) => onChangeDefault(val, index)"
            >默认收货地址</el-checkbox
          >
          <el-button
            icon="el-icon-delete"
            type="text"
            :size="size"
            @click.stop="onDel(item.addressId)"
            >删除</el-button
          >
        </div>
      </div>
    </div>
    <el-dialog
      :width="dialogWidth"
      class="address-dialog"
      :title="selectAddressId === null ? '新增地址' : '修改地址'"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form
        :model="addressForm"
        label-width="auto"
        :rules="rules"
        :size="size"
        ref="formRef"
      >
        <el-form-item label="联系人" prop="recipient">
          <el-input
            v-model="addressForm.recipient"
            placeholder="请输入联系人"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="addressForm.phone"
            placeholder="请输入联系电话"
            oninput="value=value.replace(/[^0-9.]/g,'')"
          />
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select
            v-model="addressForm.province"
            placeholder="请选择省份"
            filterable
            @change="changeProvince"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select
            v-model="addressForm.city"
            placeholder="请选择城市"
            filterable
            @change="changeCity"
          >
            <el-option
              v-for="item in cityList"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="district">
          <el-select
            v-model="addressForm.district"
            placeholder="请选择区/县"
            filterable
            @change="changeDistrict"
          >
            <el-option
              v-for="item in districtList"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="街道" prop="street">
          <el-select
            v-model="addressForm.street"
            placeholder="请选择街道"
            filterable
            @change="changeStreet"
          >
            <el-option
              v-for="item in streetList"
              :key="item.code"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="addressForm.detail" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="handleClose">取 消</el-button>
        <el-button type="primary" :size="size" @click="onSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { china } from "@/assets/ChinaCitys/ChinaCitys.js";
export default {
  name: "MyAddress",
  props: {
    isOrder: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      currentAdsId: "",
      addressList: [],
      size: "small",
      defaultAddress: 1,
      dialogVisible: false,
      screenWidth: 0,
      dialogWidth: "600px",
      selectUserId: null,
      selectAddressId: null,
      addressForm: {
        recipient: "", // 联系人
        phone: "", // 联系电话
        province: "", // 省
        city: "", // 市
        district: "", // 区/县
        street: "", // 街道
        detail: "", // 详细地址
      },
      rules: {
        recipient: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              var reg = /^1[3456789]\d{9}$/;
              if (value === "") {
                callback(new Error("请输入联系电话"));
              } else if (!reg.test(value)) {
                callback(new Error("请输入11位手机号"));
              } else {
                callback();
              }
            },
          },
        ],
        province: [
          { required: true, message: "请选择省份", trigger: "change" },
        ],
        city: [{ required: true, message: "请选择城市", trigger: "change" }],
        district: [
          { required: true, message: "请选择区/县", trigger: "change" },
        ],
        street: [{ required: true, message: "请选择街道", trigger: "blur" }],
        detail: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      provinceList: china,
      cityList: [],
      districtList: [],
      streetList: [],
    };
  },
  methods: {
    changeCurrentAdsId(id) {
      this.currentAdsId = id;
    },
    getAddressList() {
      this.$axios.get("/address/my").then((res) => {
        if (res.data.code === 200) {
          this.addressList = res.data.data;
          this.currentAdsId =
            this.addressList[0] && this.addressList[0].addressId;
        }
      });
    },
    onChangeDefault(val, index) {
      if (val === false) {
        this.$set(this.addressList[index], "isDefault", true);
      } else {
        this.$confirm("您确定要将该地址设为默认收货地址吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("/address/setDefault", {
                id: this.addressList[index].addressId,
              })
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success("设置默认地址成功");
                  this.getAddressList();
                }
              });
          })
          .catch(() => {
            this.getAddressList();
          });
      }
    },
    onAdd() {
      this.selectUserId = null;
      this.selectAddressId = null;
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
      this.dialogVisible = true;
    },
    onEdit(userId, addressId) {
      this.selectUserId = userId;
      this.selectAddressId = addressId;
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
      this.$axios.get(`/address/${userId}/address/${addressId}`).then((res) => {
        if (res.status === 200) {
          this.$set(this.addressForm, "recipient", res.data.recipient);
          this.$set(this.addressForm, "phone", res.data.phone);
          this.$set(this.addressForm, "province", res.data.province);
          this.$set(this.addressForm, "city", res.data.city);
          this.$set(this.addressForm, "district", res.data.district);
          this.$set(this.addressForm, "street", res.data.street);
          this.$set(this.addressForm, "detail", res.data.detail);
          this.cityList = this.provinceList.find(
            (item) => item.name === res.data.province
          ).citys;
          this.districtList = this.cityList.find(
            (item) => item.name === res.data.city
          ).areas;
          this.streetList = this.districtList.find(
            (item) => item.name === res.data.district
          ).towns;
          this.dialogVisible = true;
        }
      });
    },
    onDel(addressId) {
      this.$confirm("您确定要删除该地址吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.$axios.delete(`/address/delete/${addressId}`).then((res) => {
            if (res.data.code === 200) {
              this.$message.success("删除地址成功");
              this.getAddressList();
            } else {
              this.$message.error(res.data.message);
            }
          });
        })
        .catch(() => {});
    },
    handleClose() {
      this.dialogVisible = false;
      this.$set(this.addressForm, "recipient", "");
      this.$set(this.addressForm, "phone", "");
      this.$set(this.addressForm, "province", "");
      this.$set(this.addressForm, "city", "");
      this.$set(this.addressForm, "district", "");
      this.$set(this.addressForm, "street", "");
      this.$set(this.addressForm, "detail", "");
      this.$refs.formRef.clearValidate();
    },
    changeProvince(val) {
      this.addressForm.city = "";
      this.addressForm.district = "";
      this.addressForm.street = "";
      this.addressForm.detail = "";
      this.cityList = this.provinceList.find((item) => item.name === val).citys;
    },
    changeCity(val) {
      this.addressForm.district = "";
      this.addressForm.street = "";
      this.addressForm.detail = "";
      this.districtList = this.cityList.find((item) => item.name === val).areas;
    },
    changeDistrict(val) {
      this.addressForm.street = "";
      this.addressForm.detail = "";
      this.streetList = this.districtList.find(
        (item) => item.name === val
      ).towns;
    },
    changeStreet(val) {
      this.addressForm.detail = "";
    },
    onSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.selectAddressId === null) {
            this.$axios.post("/address/add", this.addressForm).then((res) => {
              if (res.data.code === 200) {
                this.$message.success("新增地址成功");
                this.getAddressList();
                this.handleClose();
              } else {
                this.$message.error(res.data.message);
              }
            });
          } else {
            this.$axios
              .put("/address/update", {
                addressId: this.selectAddressId,
                ...this.addressForm,
              })
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success("修改地址成功");
                  this.getAddressList();
                  this.handleClose();
                } else {
                  this.$message.error(res.data.message);
                }
              });
          }
        }
      });
    },
  },
  mounted() {
    this.screenWidth = document.body.clientWidth;
    window.onresize = () => {
      this.screenWidth = document.body.clientWidth;
    };
    this.getAddressList();
  },
  watch: {
    currentAdsId(val) {
      this.$emit("changeAddressId", val);
    },
    screenWidth: {
      handler(val) {
        if (val < 768) {
          this.dialogWidth = "80%";
        } else if (val < 480) {
          this.dialogWidth = "90%";
        } else {
          this.dialogWidth = "600px";
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.my-address {
  padding: 20px;
  width: 100%;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .title {
      font-size: 1.2em;
      font-weight: bold;
      text-align: left;
    }
  }

  .address-list {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;

    .address-card {
      border: 1px solid #f2f2f2;
      border-radius: 10px;
      padding: 10px;
      position: relative;

      .address-checkbox {
        position: absolute;
        top: 5px;
        right: -20px;
      }

      .address-info {
        display: flex;
        justify-content: space-between;
        text-align: left;
        align-items: center;

        .name {
          font-weight: bold;
        }

        .address-detail {
          font-size: 0.9em;
          color: #999;
          margin-top: 10px;
        }

        .el-button {
          margin-left: 20px;
        }
      }

      .address-action {
        margin-top: 10px;
        border-top: 1px solid #edebeb;
        padding-top: 10px;
        display: flex;
        justify-content: space-between;
        .el-button--text {
          padding: 0;
          color: #999;
        }
      }
    }
  }

  .address-dialog {
    text-align: left;
  }
}

.el-select {
  width: 100%;
}
</style>